﻿namespace HuwmanCode

open System
open System.Runtime.CompilerServices
open System.Management

[<AutoOpen>]
[<Extension>]
[<RequireQualifiedAccess>]
module Environment =
    /// <summary>
    /// Shut down the Operating System.
    /// </summary>
    /// <param name="reboot">Indicates whether the OS should be restarted.</param>
    /// <return></return>
    [<Extension>]
    let Shutdown reboot = 
        use win32ManagementClass = new ManagementClass("Win32_OperatingSystem")
        win32ManagementClass.Get()
        win32ManagementClass.Scope.Options.EnablePrivileges <- true

        use shutdownParams = win32ManagementClass.GetMethodParameters("Win32Shutdown")
        shutdownParams.["Flags"] <- if not <| reboot then "1" else "2"
        shutdownParams.["Reserved"] <- "0";

        for manObj in win32ManagementClass.GetInstances() do
            let x = manObj :?> System.Management.ManagementObject
            x.InvokeMethod("Win32Shutdown", shutdownParams, null) |> ignore